package sg.techstudio.suntec.main;

import java.io.Serializable;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

import sg.techstudio.suntec.dao.EmailDao;
import sg.techstudio.suntec.dao.EventContactDao;
import sg.techstudio.suntec.dao.RadiusDao;
import sg.techstudio.suntec.object.CPLoginObj;
import sg.techstudio.suntec.object.ContactDevice;
import sg.techstudio.suntec.object.Radacct;
import sg.techstudio.suntec.object.RestEventContactObj;
import sg.techstudio.suntec.object.WifiAccountObj;
import sg.techstudio.suntec.validator.BaseValidator;

@Component
public class VipEmailerMain implements Serializable {
	private static final long serialVersionUID = -3130674276918185512L;
	private static final Log log = LogFactory.getLog(VipEmailerMain.class);
	protected static String configLocation = "config/spring-context.xml";
	
	@Autowired
	private EventContactDao eDao;
	@Autowired
	private RadiusDao radiusDao;
	@Autowired
	private EmailDao emailDao;
	
	private static VipEmailerMain vipEmailerMain;
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		log.debug("start");
		
		try {
			if(args!=null && args.length>=1)
				configLocation = args[0];
			
			initProcess();
			vipEmailerMain.mainProcess();
			
		} catch(Exception e) {
			log.error("Exception at main():"+e, e);
		}
		
		log.debug("end");
	}
	
	@SuppressWarnings("resource")
	private static void initProcess() {
		log.debug("initProcess() entry");
		ApplicationContext ctx = new ClassPathXmlApplicationContext(configLocation);
		vipEmailerMain = ctx.getBean(VipEmailerMain.class);
	}
	
	private void mainProcess(){
		log.debug("mainProcess() entry");
		//get list of contact
		List<ContactDevice> cdList = eDao.getContactDeviceRemoveDuplicate();
		if(cdList==null || cdList.isEmpty()) {
			log.info("Empty list");
			return;
		}
		for(ContactDevice cd: cdList) {
			Radacct ra = radiusDao.getLastRadacct(cd);
			if(ra==null)
				continue;
			WifiAccountObj w = eDao.getWifiAccountObj(cd.getUsername());
			if(w==null) {
				log.info(String.format("wifiaccount %s not found. deleting...", cd.getUsername()));
				eDao.deleteContactDevice(cd);
				continue;
			}
			RestEventContactObj re = eDao.findEventByWifiAccount(w);
			if(re==null || re.getType()!=1 || !re.isActive()) {
				log.info(String.format("resteventcontact %s not found or invalid type. deleting...", cd.getUsername()));
				eDao.deleteContactDevice(cd);
				continue;
			}
			if(StringUtils.isNotBlank(re.getInternalEmail()) 
					&& BaseValidator.EMAIL_PATTERN.matcher(re.getInternalEmail()).matches()) {
				log.debug("sending email to "+re.getInternalEmail());
				emailDao.sendVipAlertEmail(createCpLoginObj(cd, ra, re), re.getInternalEmail());
			}
			cd.setLastradacctid(ra.getRadacctid());
			eDao.saveContactDevice(cd);
		}
		log.info("mainProcess() exit");
	}
	
	protected CPLoginObj createCpLoginObj(ContactDevice cd, Radacct ra, RestEventContactObj re) {
		CPLoginObj cp = new CPLoginObj();
		cp.setMac(cd.getMac());
		cp.setUsername(cd.getUsername());
		cp.setName(re.getName());
		cp.setIp(ra.getFramedipaddress());
		cp.setApName(ra.getCalledstationid());
		return cp;
	}

}
